package com.shopping.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.commons.dbutils.ResultSetHandler;

import com.mchange.v2.c3p0.ComboPooledDataSource;


public class BaseDao {
	
	public static Object query(String sql, ResultSetHandler<?> rsh, Object... params) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		ComboPooledDataSource cpds = new ComboPooledDataSource("shopping");
		try {
			// 获取连接
			conn = cpds.getConnection();
			// 预编译sql
			pstmt = conn.prepareStatement(sql);
			// 设置参数
			for(int i=0; params != null && i < params.length; i++) {
				pstmt.setObject(i+1, params[i]);
			}
			// 发送sql
			rs = pstmt.executeQuery();
			// 让调用者去实现对结果集的处理
			Object obj = rsh.handle(rs);
			return obj;
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			// 释放资源
			cpds.close();
		}
		return rs;
	}
}
